<template>
	<view class="doorbell-box" style="background-color: rgba(0, 0, 0, 0.95);">
		<view :style="{backgroundColor: uiType=='lexin' ? 'rgba(0, 0, 0, 0.95)': 'rgba(0, 0, 0, 0.95)'}" class="popup"
			:is-mask-click="false">
			<view v-if="callType=='FamilyCall'" class="navTitle name">{{device.deviceName}}</view>
<!--            @click="uiType == 'lexin' ? toLive() :''"-->
			<view class="u-f-ajc imgV" >
				<image class="img" :src="alarmPic" mode="aspectFit" @error="imgError()"></image>
				<!--				<image v-if="uiType == 'lexin'" class="replay" :src="replay" mode="" />-->
			</view>
			<view :style="{color:uiType == 'general'?'#fff':'#fff'}" class="bottomV u-f-ajc u-f-c">
				<view class="u-f-c u-f-ajc">
					<text v-if="callType=='FamilyCall'" class="name">家人来电</text>
					<text v-else class="name">{{device.deviceName}}</text>
					<text>等待接听</text>
				</view>
				<view class="box">
					<!--                    <view class="box" v-if="uiType == 'general'">-->
					<view class="u-f-c u-f-ac" @click="closePopup(1)">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/hangUp.png" mode=""></image>
						<text>拒绝</text>
					</view>
					<view class="u-f-c u-f-ac" @click="answerClick">
						<image class="icon" src="https://statics.xmcsrv.net/weixin/answer.png" mode=""></image>
						<text>接听</text>
					</view>
				</view>
				<!--				<view class="box lexin-box" v-if="uiType == 'lexin'">-->
				<!--					<view class="u-f-c u-f-ac" @click="cancelUnlock(1)">-->
				<!--						<image class="icon" src="https://statics.xmcsrv.net/weixin/live/operation/cancel.png" mode=""></image>-->
				<!--						<text >取消</text>-->
				<!--					</view>-->
				<!--					<view class="u-f-c u-f-ac" @click="unlocking">-->
				<!--						<image class="icon" src="https://statics.xmcsrv.net/weixin/live/operation/unlocking2.png" mode=""></image>-->
				<!--						<text >开锁{{countDown}}s</text>-->
				<!--					</view>-->
				<!--				</view>-->
			</view>
		</view>
		<uni-popup ref="unlockDialog" type="dialog">
			<view class="form">
				<view class="u-f-ajc title">是否打开门锁？</view>
				<view class="u-f-r form-item">
					<view class="u-f-ajc cancel" @click="cancel()">取消</view>
					<view class="u-f-ajc conf" @click="confimeUnlock(1,'lexin',lastMsgTime)">确认</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const {
		calculateTimeDifference
	} = require('@/utils/util.js');
	export default {
		name: "j-doorbell",
		props: {
			alarmInfo: {
				typeof: Object,
				value: () => {
					return {}
				}
			},
			hangUp: true,
			show: {
				typeof: Boolean,
				default: false
			}
		},
		data() {
			return {
				deviceNo: '',
				device: {},
				AlarmID: '',
				alarmPic: 'https://statics.xmcsrv.net/weixin/defaultMsgBg2.png',
				audioUrl: 'https://statics.xmcsrv.net/weixin/doorcall.wav',
				replay: 'https://statics.xmcsrv.net/weixin/replay.png',
				audioCtx: null,
				timerId: null,
				isHangUp: false,
				uiType: 'general',
				countDown: 60,
				countsId: null,
				maskBackgroundColor: null,
				callType:'FamilyCall',//DoorLockCall门铃来电  FamilyCall家人来电
			};
		},
		watch: {
			alarmInfo: {
				handler: function(res) {
					console.log('设备门铃来电消息==========', res);
					if (res != null) {
						if (Object.keys(res).length > 0) {
							this.deviceNo = res.SerialNumber
							this.AlarmID = res.AlarmID
							this.getDeviceListByPage()
							this.callType = res.secondAlarmEvent
						}
					}
					this.$logs({
						info: '监听门铃来电alarmInfo',
						res: res
					})
				},
				// immediate: true,
				deep: true
			},
			hangUp(val) {
				console.log('hangup===', val);
				this.isHangUp = val
			}
		},
		mounted() {
			// 监听全局事件，显示弹窗
			// uni.$off('onWebsocketMessage')
            this.$logs({info:'监听门铃来电mounted123'})
			this.storgeAudio()
			uni.$on('ondoorLockCallMessage', (res) => {
				let info = res
				console.log('监听全局事件显示弹窗', info);
				if (info) {
					if (info.propCode == "doorLockCall") {
						this.deviceNo = info.propValue.SerialNumber
						this.AlarmID = info.propValue.AlarmID
						this.AlarmTime = info.propValue.AlarmTime
						// this.getDeviceListByPage()
						// this.openPopup()
						// this.calculateTimeDifference();
					}
				}
				this.$logs({info:'监听门铃来电mounted',res:info})
			})
			uni.$on('successUnlocking', (res) => {
				// this.closePopup(1)
			})
			this.audioCtx = wx.createAudioContext('myAudio')
			this.audioCtx = wx.createInnerAudioContext({
				useWebAudioImplement: true
			})
			this.audioCtx.src = this.audioUrl
			this.audioCtx.autoplay = false
			this.audioCtx.loop = true
		},
		destroyed() {
            this.$logs({info: '门铃组件被销毁'})
			console.log('门铃销毁');
			this.closePopup(3)
		},
		onPageShow() {
            this.$logs({info: '门铃组件onPageShow'})
		    // if(this.device) {
            //     this.audioCtx.src = this.audioUrl
            //     this.audioCtx.loop = true
		    //     this.audioCtx.play()
		    // }
		},
		methods: {
            setAudioUrl() {
                this.audioCtx.src = this.audioUrl
                this.audioCtx.loop = true
                this.audioCtx.play()
            },
			// 缓存音频文件
			storgeAudio() {
				const fs = wx.getFileSystemManager()
				const that = this
				let url = uni.getStorageSync('audioUrl')
				if (!url) {
					uni.downloadFile({
						url: 'https://statics.xmcsrv.net/weixin/doorcall.wav',
						success(res) {
							console.log('下载成功后的路径', res.tempFilePath)
							fs.saveFile({
								tempFilePath: res.tempFilePath,
								success(result) {
									console.log('保存成功的路径', result.savedFilePath)
									uni.setStorageSync('audioUrl', result.savedFilePath)
									that.audioUrl = result.savedFilePath
									that.$logs({
										info: '缓存音频文件成功',
										data: result,
										url: that.audioUrl
									})
								},
								fail(err2) {
									console.log('保存失败1', err2)
									that.$logs({
										info: '保存音频文件失败',
										err: err2,
										url: that.audioUrl
									})
								},
							})
						},
						fail(err) {
							that.$logs({
								info: '下载音频文件失败',
								err: err,
								url: that.audioUrl
							})
							console.log('下载失败1', err)
						},
					})
				} else {
					this.audioUrl = url
					this.$logs({
						info: '使用本地缓存的音频文件',
						url: this.audioUrl
					})
				}
				setTimeout(() => {
					console.log(this.audioUrl)
				}, 1000)

				fs.getSavedFileList({
					success(res) {
						console.log('缓存文件列表', res)
					}
				})
			},
			//打开
			openPopup() {
				console.log(this.uiType, '来电类型')
				// if(this.uiType == 'lexin'){
				// 	this.$refs.popup.maskClass.backgroundColor = 'rgba(255, 255, 255, 0.99)';
				// }else{
				// 	this.$refs.popup.maskClass.backgroundColor = 'rgba(0, 0, 0, 0.95)';
				// uni.setNavigationBarColor({
				// 	frontColor: "#000000",
				// 	backgroundColor: '#000000'
				// })
				// }
				// this.$refs.popup.open()
				this.$parent.show = true

				// this.audioCtx.src = this.audioUrl
				// this.audioCtx.play()
				// this.audioCtx.loop = true
				// uni.hideTabBar();
				// this.audioCtx.onPlay((res)=>{
				// 	console.log('开始播放音频',res);
				// })
				// this.audioCtx.onError((err)=>{
				// 	console.log('播放音频报错',err);
				// 	this.$logs({info:'公众号门铃来电j-doorbell打开播放音频报错',res:err},'error')
				// })
				// this.audioCtx.onEnded((err)=>{
				// 	console.log('播放音频结束',err);
				// })
				this.$logs({
					info: '公众号门铃来电j-doorbell打开成功'
				}, 'info')
				let time = this.uiType == 'lexin' ? 600000 : 15000
				// if(this.uiType == 'lexin'){
				// 	this.countDown = calculateTimeDifference(this.AlarmTime,1);
				// 	console.log(this.countDown,'秒数')
				// 	this.countsId = setInterval(()=>{
				// 		this.countDown -- ;
				// 		if(this.countDown == 0){
				// 			clearInterval(this.countsId);
				// 			this.closePopup(1)
				// 			this.countDown == 60;
				// 			this.audioCtx.pause()
				// 		}
				// 	},1000)
				// }else{
				// 	this.timerId = setTimeout(()=>{
				// 		if(!this.isHangUp){
				// 			this.closePopup(2)f
				// 		}
				// 		this.audioCtx.pause()
				// 	},15000)
				// }
				console.log('开始打印门兴setTimeout')
				this.timerId = setTimeout(() => {
					console.log(this.isHangUp, '门铃')
					if (!this.isHangUp) {
						this.closePopup(2)
					}
					this.audioCtx.pause()
				}, 15000)
			},
			//挂断
			closePopup(type) {
				if (this.audioCtx) {
					this.audioCtx.pause()
					this.audioCtx.src = ''
					this.audioCtx.loop = false
				}
				// 关闭弹框时再设置回原来的颜色
				// uni.setNavigationBarColor({
				// 	frontColor: "#000000",
				// 	backgroundColor: '#f8f8f8',
				// })

				clearTimeout(this.timerId)
				this.timerId = null
				clearInterval(this.countsId);
				this.countsId = null
				this.countDown = 60;

				// this.$refs.popup.close()
				console.log(this.$parent.show, '父组件show的值')
				// this.$parent.show = false

				uni.showTabBar()
				//1 手动挂断  2自动挂断
				this.isHangUp = type == 1 ? true : false
				if (type != 3) {
					this.$emit('hangUp', this.device)
				}
				console.log('已挂断', this.timerId, this.countsId, this.countDown, this.audioCtx, this.isHangUp, type);
				this.$logs({
					info: '已挂断',
					data: this.device,
					isHangUp: this.isHangUp,
					type: type
				})
			},
			// 取消
			cancelUnlock() {
				this.closePopup(1)
			},
			toLive() {
				console.log('????????????')
				let data = this.device
				let url =
					`/jvss/pagesDevice/device/device-live/door-lock/live-lexin2?device=${encodeURIComponent(JSON.stringify(data))}&type=${'doorbell'}&AlarmTime=${this.AlarmTime}&operation=${'unlocking'}`
				uni.reLaunch({
					url: url
				})
				setTimeout(res => {
					this.closePopup(1)
				}, 200)
			},
			// 开锁
			unlocking() {
				// this.getLogin()
				this.$refs.unlockDialog.open();
			},
			confimeUnlock() {
				this.cancel();
				uni.showLoading({
					title: '加载中...',
					mask: true
				});
				let data = {
					encryptType: 'DISABLE',
					LoginType: 'DVRIP-Web',
					UserName: this.device.devUserName,
					PassWord: this.device.devPassWord,
					Name: 'generalinfo',
					KeepaliveTime: 20
				};
				if (this.device.adminToken) {
					data.LoginToken = this.device.adminToken
					data.encryptType = 'TOKEN'
				}
				let token = this.device.token
				getApp().globalData.api.deviceLogin(data, token, (result) => {
					uni.hideLoading();
					if (result.data.code === 2000) {
						let Ret = result.data.data.Ret
						if (Ret === 100 || Ret === 104) {
							this.getUnlock()
						} else if (Ret === 137) {
							uni.showToast({
								title: getApp().globalData.errCodeMsg.RetCodeMsg[Ret] || result.data
									.data.RetMsg,
								icon: "none"
							})
						}
						// 出错
						else {
							uni.showToast({
								title: getApp().globalData.errCodeMsg.RetCodeMsg[Ret] ||
									result.data.data.RetMsg,
								icon: "none"
							})
						}
					}
					// 4000 参数错误
					else if (result.data.code === 4000) {
						uni.showToast({
							title: result.data.msg,
							icon: 'none',
							success: (res) => {}
						});

					}
				});
			},
			// 取消开锁
			cancel() {
				this.$refs.unlockDialog.close()
			},
			getUnlock() {
				let token = this.device.token;
				let data = {
					sn: this.device.deviceNo,
					props: {
						"doorLock": {
							"remoteOneKeyUnlock": 1
						}
					}
				};
				getApp().globalData.api.remoteUnlock(data, token, (result) => {
					uni.hideLoading();
					if (result.Ret === 100) {
						setTimeout(() => {
							uni.showToast({
								title: '开锁成功',
							});
						}, 500)
					} else {
						uni.showToast({
							title: '开锁失败',
							icon: 'error'
						});
					}
				});
			},
			//接听
			answerClick() {
				this.closePopup(3)
				this.$emit('answerClick', this.device)
				let constant = getApp().globalData.constant;
				// EE_DEV_SMARTDOORLOCK3: 'HAVLS00090001007' ,// 雄迈650V200屏显智能云锁 博克定制AHD门锁主pid
				// EE_DEV_SMARTDOORLOCK7: 'HAVLS0013000100C' ,// 乐鑫屏显智能云锁 博克定制乐鑫门锁主pid
				let LOCK = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK;
				let LOCK2 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK2;
				let LOCK3 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK3;
				let LOCK4 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK4;
				let LOCK5 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK5;
				let LOCK6 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK6;
				let LOCK7 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK7;
				let LOCK8 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK8;
				let LOCK9 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK9;
				let LOCK10 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK10;
				let LOCK11 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK11;
				let LOCK12 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK12;
				let LOCK13 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK13;
				let LOCK14 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK14;
				let LOCK15 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK15;
				let LOCK16 = constant.DEVICE_TYPE.EE_DEV_SMARTDOORLOCK16;
				let url = ''
				let data = this.device
				if (data.parentPid === LOCK5 || data.parentPid == LOCK7 || data.parentPid == LOCK12 || data.parentPid ==
					LOCK10) {
					url =
						`/jvss/pagesDevice/device/device-live/door-lock/live-lexin?type=3&device=${encodeURIComponent(JSON.stringify(data))}`
				} else if (data.parentPid === LOCK3 || data.parentPid == LOCK || data.parentPid == LOCK2) {
					url =
						`/jvss/pagesDevice/device/device-live/door-lock/live1?type=3&device=${encodeURIComponent(JSON.stringify(data))}`
				} else if (data.pid == LOCK4 || data.parentPid == LOCK4 || data.parentPid == LOCK11 || data.parentPid == LOCK9) {
					url =
						`/jvss/pagesDevice/device/device-live/door-lock/live-lexin2?type=3&device=${encodeURIComponent(JSON.stringify(data))}`
				} else {
					url =
						`/jvss/pagesDevice/device/device-live/live/live?type=3&device=${encodeURIComponent(JSON.stringify(data))}`
				}
				if(this.callType == 'FamilyCall'){
					url = `/jvss/pagesDevice/device/device-live/door-lock/live-familyCall?type=3&device=${encodeURIComponent(JSON.stringify(data))}`
				}
				console.log('家人来电跳转===',data);
				this.voesCallHangup(()=>{
					uni.reLaunch({
						url: url
					})
				})
				this.$logs({
					info: '接听',
					data: this.device
				})
			},
			// 接听的时候需要挂断云电话
			voesCallHangup(callback) {
				let token = this.device.token
				let data = {
					userId: uni.getStorageSync('userInfo').userId,
					sn: this.device.deviceNo
				}
				getApp().globalData.api.voesCallHangup(data, token, (result) => {
					if(typeof callback == 'function'){
						callback(result)
						this.$logs({
							info: '公众号跳转接听门铃来电时挂断云电话',
							data: this.device
						})
					}
				});
			},
			//获取设备信息
			getDeviceListByPage() {
				const data = {
					page: 1,
					limit: 999,
					deviceNo: this.deviceNo
				};
				getApp().globalData.api.getUserDeviceListByPage(data, (result) => {
					if (result.data.length > 0) {
						result.data.forEach((item) => {
							if (item.deviceNo == this.deviceNo) {
								this.device = item
							}
						})
						if (this.device.localUiKey == "ui_doorlock_home") {
							this.uiType = 'lexin'
						}
						setTimeout(() => {
							console.log(this.device.localUiKey, this.uiType, '门铃来电设备信息')
							if (this.countsId) {
								clearInterval(this.countsId);
								this.countDown == 60;
							}
							// if(this.timerId){
							// 	clearInterval(this.timerId);
							// }
						}, 50)
					}
					// this.openPopup()
					this.getDeviceToken([this.deviceNo])
				});
			},
			//获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {
					this.device.token = result[0].token
					this.getDeviceStatus([result[0].token])
					this.getImgUrl([this.AlarmID], this.device.token)
				});
			},
			// 获取设备状态
			getDeviceStatus(tokenList) {
				const data = {
					token: tokenList
				};
				getApp().globalData.api.getDeviceStatus(data, (result) => {
					this.device.status = result[0]
				})
			},
			//获取图片
			getImgUrl(data, token) {
				getApp().globalData.api.getPicUrl(data, token, (result) => {
					let res = result.data
					if (res.code == 2000) {
						let defaultImg = 'https://statics.xmcsrv.net/weixin/defaultMsgBg2.png'
						this.alarmPic = res.data.length > 0 ? res.data[0].url : defaultImg
					}
				}, false, false);
			},
			//加载图片失败
			imgError() {
				this.alarmPic = 'https://statics.xmcsrv.net/weixin/defaultMsgBg2.png'
			},
		}
	}
</script>

<style lang="scss" scoped>
	.popup {
		/deep/ .uni-popup {
			z-index: 9999;
		}
	}

	.doorbell-box {
		width: 100%;
		height: 100%;
		position: fixed;
		//background-color:rgba(0, 0, 0, 0.99);
	}
	.navTitle{
		margin:40rpx ;
		color: white;
	}
	.imgV {
		// position: relative;
		width: 90%;
		height: calc(100vh - 400rpx);
		position: fixed;
		top: 0rpx;
		//margin-left: -45%;
		left: 50%;
		transform: translate(-50%);
	}

	.img {
		width: 100%;
		height: calc(100vh - 400rpx);
		// position: fixed;
		// top: 0rpx;
	}

	.replay {
		position: absolute;
		width: 100rpx;
		height: 100rpx;
		top: 50%;
		margin-top: -50rpx;
		left: 50%;
		margin-left: -50rpx;
	}

	.bottomV {

		position: fixed;
		bottom: 80rpx;
		left: 0;
		right: 0;
		height: 220rpx;
		color: white;

		.name {
			font-size: 32rpx;
			width: 100%;
			text-align: center;
			word-break: break-all;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			-webkit-line-clamp: 2;
			text-overflow: ellipsis;
			overflow: hidden;
			margin-bottom: 10rpx;
		}

		.box {
			width: 80%;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.lexin-box {
			width: 100%;
			justify-content: space-around;
		}

		.icon {
			width: 120rpx;
			height: 120rpx;
		}
	}

	.form {
		background: white;
		padding: 40rpx 40rpx;
		border-radius: 40rpx;

		.title {
			font-size: 34rpx;
			font-weight: bold;
			line-height: 49rpx;
			color: #464646;
		}

		.form-item {
			margin-top: 80rpx;

			.cancel {
				background: #F6F7FB;
				color: #000000;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
			}

			.conf {
				margin-left: 20rpx;
				background: #FF0025;
				color: #ffffff;
				font-size: 30rpx;
				width: 237rpx;
				height: 84rpx;
				border-radius: 42rpx;
			}
		}
	}
</style>
